(function () {
    'use strict';

    let isMobile = false;

    // init toolbar
    // =======================

    let designWidth = _CCSettings.designWidth;
    let designHeight = _CCSettings.designHeight;

    let rotated = false;
    // var paused = false;
    let canvas = document.getElementById('GameCanvas');

    function isFullScreen () {
        // var toolbar = document.getElementsByClassName('toolbar')[0];
        // return getComputedStyle(toolbar).display === 'none';
        return true;
    }

    function showSplash () {
        let div = document.getElementById('GameDiv');
        if (div) {
            div.style.visibility = 'visible';
        }

        let size = document.body.getBoundingClientRect();
        canvas.width = size.width;
        canvas.height = size.height;
    }


    window.onload = function () {
        if (window.__quick_compile_engine__) {
            window.__quick_compile_engine__.load(onload);
        }
        else {
            onload();
        }
    };

    function onload () {

        // socket
        // =======================

        // jshint camelcase:false

        let socket = window.__socket_io__();
        socket.on('browser:reload', function () {
            window.location.reload();
        });
        socket.on('browser:confirm-reload', function () {
            let r = confirm( 'Reload?' );
            if ( r ) {
                window.location.reload();
            }
        });

        function updateResolution () {
            let size = document.body.getBoundingClientRect();
            let gameDiv = document.getElementById('GameDiv');
            // gameDiv.style.width = size.width + 'px';
            // gameDiv.style.height = size.height + 'px';
            gameDiv.style.width = '480px';
            gameDiv.style.height = '800px';
            cc.view.setCanvasSize(size.width, size.height);
        }

        // init engine
        // =======================

        let engineInited = false;

        if (isFullScreen()) {
            window.addEventListener('resize', updateResolution);
        }

        // let showFPS = getCookie('showFPS');
        // // FPS is on by default
        // showFPS = showFPS === null ? true : showFPS === 'true';

        let onStart = function () {
            // resize canvas
            // if (!isFullScreen()) {
            //     updateResolution();
            // }
            updateResolution();

            cc.view.enableRetina(true);
            cc.view.resizeWithBrowserSize(true);

            // Loading splash scene
            let splash = document.getElementById('splash');
            let progressBar = splash.querySelector('.progress-bar span');
            showSplash();

            cc.director.once(cc.Director.EVENT_AFTER_SCENE_LAUNCH, function () {
                splash.style.display = 'none';
                checkEmptyScene();
            });

            cc.game.pause();

            // init assets
            engineInited = true;

            cc.assetManager.loadAny({url: 'preview-scene.json', __isNative__: false }, null, function (finish, totalCount) {
                    var percent = 100 * finish / totalCount;
                    if (progressBar) {
                        progressBar.style.width = percent.toFixed(2) + '%';
                    }
                }, function (err, sceneAsset) {
                if (err) {
                    console.error(err.message, err.stack);
                    return;
                }
                var scene = sceneAsset.scene;
                scene._name = sceneAsset._name;
                // HACK: Change key to uuid from url
                cc.assetManager.dependUtil._depends.add(scene._id, cc.assetManager.dependUtil._depends.get('preview-scene.json'));
                cc.director.runSceneImmediate(scene, function () {
                    // play game
                    cc.game.resume();
                });
            });

            // purge
            //noinspection JSUnresolvedVariable
            _CCSettings = undefined;

            updateResolution();
        };

        var option = {
            id: canvas,
            debugMode: 1,
            showFPS: true,
            frameRate: 60,
            groupList: _CCSettings.groupList,
            collisionMatrix: _CCSettings.collisionMatrix,
        };

        cc.assetManager.init({
            importBase: 'assets/others/import',
            nativeBase: 'assets/others/native'
        });

        let { RESOURCES, INTERNAL, MAIN } = cc.AssetManager.BuiltinBundleName;
        let bundleRoot = [INTERNAL, MAIN];
        _CCSettings.hasResourcesBundle && bundleRoot.push(RESOURCES);

        var count = 0;
        function cb (err) {
            if (err) return console.error(err);
            count++;
            if (count === bundleRoot.length + 1) {
                cc.game.run(option, onStart);
            }
        }

        // load plugins
        cc.assetManager.loadScript(_CCSettings.jsList.map(function (x) { return '/plugins/' + x; }), cb);

        // load bundles
        for (let i = 0; i < bundleRoot.length; i++) {
            cc.assetManager.loadBundle(bundleRoot[i], cb);
        }
    };

    function checkEmptyScene () {
        var scene = cc.director.getScene();
        if (scene) {
            if (scene.children.length > 1) {
                return;
            }
            if (scene.children.length === 1) {
                var node = scene.children[0];
                if (node.children.length > 0) {
                    return;
                }
                if (node._components.length > 1) {
                    return;
                }
                if (node._components.length > 0 && !(node._components[0] instanceof cc.Canvas)) {
                    return;
                }
            }
        }
        document.getElementById('bulletin').style.display = 'block';
        document.getElementById('sceneIsEmpty').style.display = 'block';
    }
})();

